﻿var spdevlab = spdevlab || {};
spdevlab.fieldSamples = spdevlab.fieldSamples || {};

// visa field validator impl
spdevlab.fieldSamples.DateBirthFieldValidator = function () {

    spdevlab.fieldSamples.DateBirthFieldValidator.prototype.Validate = function (value) {

        var hasError = value == "";
        var errorMsg = hasError ? "Please, fill out birthdate." : '';

        return new SPClientForms.ClientValidation.ValidationResult(hasError, errorMsg);
    };
};

// date birth field impl
spdevlab.fieldSamples.DateBirthField = function () {

    var self = this;

    spdevlab.fieldSamples.DateBirthField.prototype._fieldName = "";
    spdevlab.fieldSamples.DateBirthField.prototype._errorContainerId = null;

    spdevlab.fieldSamples.DateBirthField.prototype._monthContainerId = "";
    spdevlab.fieldSamples.DateBirthField.prototype._dayContainerId = "";
    spdevlab.fieldSamples.DateBirthField.prototype._yearContainerId = "";

    spdevlab.fieldSamples.DateBirthField.prototype._onGetValue = function () {

        var result = '';

        var monthContainer = document.getElementById(self._monthContainerId);
        var dayContainer = document.getElementById(self._dayContainerId);
        var yearContainer = document.getElementById(self._yearContainerId);

        var dValue = dayContainer.options[dayContainer.selectedIndex].value;
        var mValue = monthContainer.options[monthContainer.selectedIndex].value;
        var yValue = yearContainer.options[yearContainer.selectedIndex].value;

        if (dValue > -1 && mValue > -1 && yValue > -1) {
            return mValue.toString() + "/" +
        			dValue.toString() + "/" +
       				yValue.toString();
        }

        return "";
    };



    spdevlab.fieldSamples.DateBirthField.prototype._initValidators = function (renderCtx) {

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);

        var dbfFieldValidators = new SPClientForms.ClientValidation.ValidatorSet();

        if (formCtx.fieldSchema.Required) {
            dbfFieldValidators.RegisterValidator(new spdevlab.fieldSamples.DateBirthFieldValidator());
        }

        formCtx.registerValidationErrorCallback(formCtx.fieldName, self.onError);
        formCtx.registerClientValidator(formCtx.fieldName, dbfFieldValidators);
    };

    spdevlab.fieldSamples.DateBirthField.prototype._getDateTimeValue = function (fieldValue) {

        var result = {
            activeDay: -1,
            activeMonth: -1,
            activeYear: -1
        };

        if (typeof fieldValue !== "undefined") {

            var dateParts = [];

            if (fieldValue.indexOf(":") > -1) {
                dateParts = fieldValue.split(" ")[0].split('/');
            }
            else {
                dateParts = fieldValue.split("/");
            }

            result.activeMonth = dateParts[0];
            result.activeDay = dateParts[1];
            result.activeYear = dateParts[2];
        }

        return result;
    }

    spdevlab.fieldSamples.DateBirthField._months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    spdevlab.fieldSamples.DateBirthField.prototype._getUI = function (monthContainerId, dayContainerId, yearContainerId, fieldValue) {

        var result = [];

        var timeValue = self._getDateTimeValue(fieldValue);
        var months = spdevlab.fieldSamples.DateBirthField._months;

        // month UI		
        result.push("<select id='" + monthContainerId + "' type='singleselect'>");
        result.push("<option value='-1'>Month...</option>");

        for (var i = 0; i < months.length; i++) {
            var isSelected = (timeValue.activeMonth > -1 && (i + 1) == timeValue.activeMonth) == true ? "selected" : "";
            result.push("<option value='" + (i + 1).toString() + "' " + isSelected + ">" + months[i].toString() + "</option>");
        }

        result.push("</select>");

        // day UI		
        result.push("<select id='" + dayContainerId + "' type='singleselect'>");
        result.push("<option value='-1'>Day...</option>");
        for (var i = 1; i <= 31; i++) {
            var isSelected = (timeValue.activeDay > -1 && (i) == timeValue.activeDay) == true ? "selected" : "";
            result.push("<option value='" + i.toString() + "' " + isSelected + ">" + i.toString() + "</option>");
        }
        result.push("</select>");

        result.push(" | ");

        // year UI		
        result.push("<select id='" + yearContainerId + "' type='singleselect'>");
        result.push("<option value='-1'>Choose...</option>");
        for (var i = 2013; i >= 1905; i--) {
            var isSelected = (timeValue.activeYear > -1 && (i) == timeValue.activeYear) == true ? "selected" : "";
            result.push("<option value='" + i.toString() + "' " + isSelected + ">" + i.toString() + "</option>");
        }
        result.push("</select>");

        return result.join("");
    };


    spdevlab.fieldSamples.DateBirthField.prototype.newFormTemplate = function (renderCtx) {

        self._initValidators(renderCtx);

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
        formCtx.registerGetValueCallback(formCtx.fieldName, self._onGetValue);

        var containerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + 'DateBirth_Field';

        self._monthContainerId = containerId + "_Month";
        self._dayContainerId = containerId + "_Day";
        self._yearContainerId = containerId + "_Year";

        return self._getUI(self._monthContainerId, self._dayContainerId, self._yearContainerId) + self._wrapErrorArea(renderCtx);
    };

    spdevlab.fieldSamples.DateBirthField.prototype.editFormTemplate = function (renderCtx) {

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
        var fieldValue = renderCtx.CurrentItem[renderCtx.CurrentFieldSchema.Name];

        self._initValidators(renderCtx);

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
        formCtx.registerGetValueCallback(formCtx.fieldName, self._onGetValue);

        var containerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + 'DateBirth_Field';

        self._monthContainerId = containerId + "_Month";
        self._dayContainerId = containerId + "_Day";
        self._yearContainerId = containerId + "_Year";

        return self._getUI(self._monthContainerId, self._dayContainerId, self._yearContainerId, fieldValue) + self._wrapErrorArea(renderCtx);
    };

    spdevlab.fieldSamples.DateBirthField.prototype.displayFormTemplate = function (renderCtx) {

        if (renderCtx != null && renderCtx.CurrentFieldValue != null) {

            var fieldValue = renderCtx.CurrentFieldValue.toString();

            var timeValue = self._getDateTimeValue(fieldValue);

            if (timeValue.activeDay > -1 && timeValue.activeMonth > -1 && timeValue.activeYear > -1) {
                return spdevlab.fieldSamples.DateBirthField._months[timeValue.activeMonth - 1].toString() + " " +
					   timeValue.activeDay.toString() + ", " +
					   timeValue.activeYear.toString();
            }

            return fieldValue;
        }

        return '';
    };

    spdevlab.fieldSamples.DateBirthField.prototype.viewTemplate = function (renderCtx, field, listItem, listSchema) {

        var fieldValue = "";

        if (renderCtx != null && renderCtx.CurrentItem != null) {
            fieldValue = renderCtx.CurrentItem[field.Name];
            var timeValue = self._getDateTimeValue(fieldValue);

            if (timeValue.activeDay > -1 && timeValue.activeMonth > -1 && timeValue.activeYear > -1) {
                return spdevlab.fieldSamples.DateBirthField._months[timeValue.activeMonth - 1].toString() + " " +
					   timeValue.activeDay.toString() + ", " +
					   timeValue.activeYear.toString();
            }
        }

        return fieldValue;
    };

    spdevlab.fieldSamples.DateBirthField.prototype._wrapErrorArea = function (renderCtx) {

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
        var errorContainerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + '_DateBirth_Error';

        self._errorContainerId = errorContainerId;

        return "<div></div><span id='" + errorContainerId + "' class='ms-formvalidation ms-csrformvalidation'></span>";
    };

    spdevlab.fieldSamples.DateBirthField.prototype.onError = function (error) {

        if (self._errorContainerId != null) {

            document
                .getElementById(self._errorContainerId)
                .innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
        }
    };

    spdevlab.fieldSamples.DateBirthField.prototype.init = function (targetFieldName) {

        self._fieldName = targetFieldName;

        var fieldName = self._fieldName;
        var bdtFieldTemplates = {};

        bdtFieldTemplates["Templates"] = {};
        bdtFieldTemplates.Templates["Fields"] = {};

        bdtFieldTemplates.Templates.Fields[fieldName] = {};

        bdtFieldTemplates.Templates.Fields[fieldName]["View"] = self.viewTemplate;
        bdtFieldTemplates.Templates.Fields[fieldName]["NewForm"] = self.newFormTemplate;
        bdtFieldTemplates.Templates.Fields[fieldName]["EditForm"] = self.editFormTemplate;
        bdtFieldTemplates.Templates.Fields[fieldName]["DisplayForm"] = self.displayFormTemplate;

        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(bdtFieldTemplates);
    };
};

(function () {
    var dbfField = new spdevlab.fieldSamples.DateBirthField();
    dbfField.init("DateBirthField");
})();